<template>
  <el-row justify="center" align="middle" class="h-screen">
    <el-col :span="8" :offset="0">
      <el-card class="box-card">
        <template #header>
          <div class="card-header flex justify-between items-center">
            <span>锋选菁英管理平台</span>
            <el-button class="button" text>联系管理员</el-button>
          </div>
        </template>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          status-icon
          :rules="rules"
          class="demo-ruleForm"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="ruleForm.password"
              type="password"
              autocomplete="off"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)"
              >Submit</el-button
            >
            <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { AccountType } from "../types/user";
import { useAccount } from "../store/user";
// 获取表单对象
const ruleFormRef = ref<FormInstance>();
// 自定义表单验证函数
const validateName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请输入账号"));
  }
  callback();
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码")); //验证失败
  } else {
    callback(); //通过验证
  }
};
//表单数据
const ruleForm: AccountType = reactive({
  username: "张三丰",
  password: "123",
});

// 表单验证规则
const rules = reactive<FormRules<typeof ruleForm>>({
  password: [{ validator: validatePass, trigger: "blur" }],
  username: [{ validator: validateName, trigger: "blur" }],
});

// 表单提交事件
const user = useAccount();
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!"); //表单验证通过
      console.log(ruleForm);
      user.loginAction(ruleForm);
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style scoped>
.h-screen :deep(.el-form-item__content) {
  justify-content: center;
  /* border: 1px solid red; */
}
</style>
